class code3 {
    //dfs模板转换
    //越界+1
    //遇到为海洋+1

    public static int m;
    public static int n;

    public int islandPerimeter(int[][] grid) {
        m = grid.length;
        n = grid[0].length;
        int ret = 0;

        for(int i=0;i<m;i++) {
            for(int j=0;j<n;j++) {
                if(grid[i][j] == 1) {
                    ret += dfs(grid,i,j);
                }
            }
        }
        return ret;
    }
    private int dfs(int[][] grid,int x,int y) {
        //出口
        if(board(x,y)) {
            return 1;
        }

        if(grid[x][y] == 0) {
            return 1;
        }

        if(grid[x][y] != 1) {
            return 0;
        }

        grid[x][y] = 2;

        return dfs(grid,x+1,y) + dfs(grid,x-1,y) + dfs(grid,x,y+1) + dfs(grid,x,y-1);
    }

    private boolean board(int x,int y) {
        if(x<0 || x>=m || y<0 || y>=n) {
            return true;
        }
        return false;
    }
}